import json

from fastapi import Depends

from app.core.BaseResponse import success, fail
from app.service.jwt_service import get_current_user
from app.service.menu import get_menu_names, get_menu
from app.service.response import response_navs, response_manage_media, response_user, response_detail_media
from app.service.search import search_home_media
from app.service.system import get_sys_config
from app.service.user import get_history_search_words, empty_history_search_words
from app.settings.config import LIMIT
from app.validator.app import schemas


async def empty():
    """
    空方法
    :return:
    """
    return success({})


async def recommend_medias(
        page: int = 1,
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    limit = LIMIT
    offset = (page - 1) * limit

    # TODO 模拟数据
    # banners
    banners = [
        {
            "media": {
                "key": "photo/5c3aa68ceb6c2536d48063cc/c7e6e24a3e874b9a5713c687c46d05147580a63f",
                "width": 1200,
                "height": 801,
                "type": "image/jpg",
                "videoWidth": 1200,
                "videoHeight": 801,
                "url": "http://media.zc0901.com/photo/5c3aa68ceb6c2536d48063cc/c7e6e24a3e874b9a5713c687c46d05147580a63f?imageMogr2/auto-orient/thumbnail/!860x280r/sharpen/1/gravity/Center/crop/860x280/format/jpg/blur/1x0/quality/90",
                "originalUrl": "http://media.zc0901.com/photo/5c3aa68ceb6c2536d48063cc/c7e6e24a3e874b9a5713c687c46d05147580a63f",
            },
            "url": "https://www.baidu.com"
        }
    ]

    # TODO 模拟数据
    total, infos = await search_home_media({
        "offset": offset,
        "limit": limit,
        "keyword": "",
        "must_tags": [],
        "should_tags": [],
        "media_type": 0,
        "whole_case": False,
    })
    items = []
    for info in infos:
        # media_type = info.get('type')
        media_id = info.get('media_id')
        item = await response_manage_media(current_user.id, media_id)
        if item:
            items.append(item)
    data = {
        "banners": banners,
        "list": items
    }
    return success(data)


async def follow_followers(
        page: int = 1,
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    limit = LIMIT
    offset = (page - 1) * limit
    # 获取关注用户
    user_ids = [1]
    users = []
    for user_id in user_ids:
        user = await response_user(current_user.id, user_id)
        if user:
            users.append(user)

    # TODO 模拟数据
    # 推荐的规则：1、没有关注的人，则默认推荐一批信息，2、有关注的人，显示关注人的信息
    total, infos = await search_home_media({
        "offset": offset,
        "limit": limit,
        "keyword": "",
        "must_tags": [],
        "should_tags": [],
        "media_type": 0,
        "whole_case": False,
    })
    items = []
    for info in infos:
        # media_type = info.get('type')
        media_id = info.get('media_id')
        item = await response_detail_media(current_user.id, media_id, photo_limit=3)
        if item:
            items.append(item)
    data = {
        "users": users,
        "recommendList": items,
    }
    return success(data)


async def index_items(
        page: int = 1,
        menuId: int = 0,
        subMenuId: str = '',
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    limit = LIMIT
    offset = (page - 1) * limit
    menu_id = menuId
    sub_menu_ids = list(filter(bool, map(int, subMenuId.strip().split(',')))) if subMenuId.strip() else []

    menu = await get_menu(menu_id)
    if not menu:
        return fail(-1, '主菜单不存在')

    params = {
        "offset": offset,
        "limit": limit,
        "must_tags": [],
        "should_tags": [],
        "media_type": 0,
        "whole_case": None,
    }

    menu_ids = []
    if menu.name in ['关注', '推荐']:
        return fail(-1, '此主菜单无数据')
    elif menu.name in ['全屋案例', '3D全景']:  # 整屋
        if menu.name == '全屋案例':
            params['whole_case'] = True
        if menu.name == '3D全景':
            params['media_type'] = 5
        menu_ids.extend(sub_menu_ids)
    else:  # 空间类  只搜索图片
        params['media_type'] = 1
        menu_ids.append(menu_id)
        menu_ids.extend(sub_menu_ids)

    navs = await response_navs(menu_id, sub_menu_ids)
    # 获取选中的菜单名称
    names = await get_menu_names(menu_ids)

    # 去除"全部"字眼的菜单选项
    must_tags = []
    for name in names:
        if name.find('全部') != -1:
            continue
        must_tags.append(name)
    params['must_tags'] = must_tags

    total, infos = await search_home_media(params)
    items = []
    for info in infos:
        # media_type = info.get('type')
        media_id = info.get('media_id')
        item = await response_manage_media(current_user.id, media_id)
        if item:
            items.append(item)
    data = {
        'navs': navs,
        'list': items
    }
    return success(data)


async def search_related_words(
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    return success([])


async def search_items(
        page: int = 1,
        menuId: int = 0,
        subMenuId: str = '',
        keyword: str = '',
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    return success({})


async def search_image_upload(
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    return success({})


async def search_image(
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    return success({})


async def search_history(
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    history_words = await get_history_search_words(current_user.id)
    c = await get_sys_config('hot_search_words')
    hot_words = []
    if c:
        hot_words = json.loads(c.value) if c.value else []
    data = {
        'history': history_words,
        'hot': hot_words
    }
    return success(data)


async def delete_search_history(
        current_user: schemas.User = Depends(get_current_user),
):
    """"""
    await empty_history_search_words(current_user.id)
    return success({})
